package com.liuhengjia.langchain4japply.api;

import com.liuhengjia.langchain4japply.config.assistant.Assistant;
import dev.langchain4j.data.message.UserMessage;
import dev.langchain4j.memory.ChatMemory;
import dev.langchain4j.memory.chat.MessageWindowChatMemory;
import dev.langchain4j.model.chat.ChatLanguageModel;
import dev.langchain4j.model.chat.response.ChatResponse;
import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

/**
 * 会话记忆 API
 */
@RestController
@RequestMapping("/api/memory")
@RequiredArgsConstructor
public class MemoryAPI {
    private final ChatLanguageModel chatLanguageModel;
    private final ChatMemory chatMemory = MessageWindowChatMemory.builder().maxMessages(10).build();
    private final Assistant memoryAssistant;

    /**
     * 低级聊天
     *
     * @param message 用户信息
     * @return 模型响应
     */
    @GetMapping("/low/chat")
    public String lowChat(@RequestParam(value = "message") String message) {
        chatMemory.add(UserMessage.from(message));
        ChatResponse chatResponse = chatLanguageModel.chat(chatMemory.messages());// ！！！
        chatMemory.add(chatResponse.aiMessage());
        return chatResponse.aiMessage().text();
    }

    /**
     * 高级聊天
     *
     * @param message 用户信息
     * @return 模型响应
     */
    @GetMapping("/high/chat")
    public String highChat(@RequestParam(value = "message") String message) {
        return memoryAssistant.chat(message);
    }
}
